<script setup lang="ts">
import { getTableDataApi } from "@/api/task/index"
import { TableData } from "@/api/task/types/task"
import { usePagination } from "@/hooks/usePagination"
import { ElMessage, ElTable, FormInstance } from "element-plus"
import { computed, reactive, ref, watch } from "vue"
import { taskModeOptions, TabTypeEnum, TASK_MODE } from "@/constants/other-keys"
import { Search } from "@element-plus/icons-vue"
import { dataAccessApi } from "@/api/resources/source/index"
import { find } from "xe-utils"

interface Props {
  visible: boolean
}
const props = defineProps<Props>()
const emit = defineEmits(["closeDialog"])
const dialogVisible = ref<boolean>(false)
const loading = ref<boolean>(false)
const tableData = ref<TableData[]>([])
const searchFormRef = ref<FormInstance | null>(null)
const searchData = reactive({
  task_name: undefined,
  task_type: undefined,
  task_mode: undefined,
  task_status: undefined,
  publish_time: undefined,
  end_time: undefined
})
const task_id = ref<string>()
const currentRow = ref()
const singleTableRef = ref<InstanceType<typeof ElTable>>()

const { paginationData, handleCurrentChange, handleSizeChange } = usePagination()

const setCurrent = (row?: TableData) => {
  singleTableRef.value!.setCurrentRow(row)
}
const handleRowChange = (val: TableData | undefined) => {
  currentRow.value = val
  task_id.value = val?.task_id
}
const handleSearch = () => {
  paginationData.currentPage === 1 ? getTableData() : (paginationData.currentPage = 1)
}
const resetSearch = () => {
  searchFormRef.value?.resetFields()
  handleSearch()
}
//#endregion

const getTableData = () => {
  loading.value = true
  getTableDataApi({
    size: paginationData.pageSize,
    current_page: paginationData.currentPage,
    task_name: searchData.task_name || undefined,
    task_type: TabTypeEnum.DYNAMIC,
    task_mode: searchData.task_mode,
    task_status: searchData.task_status || undefined,
    publish_time: searchData.publish_time || undefined,
    end_time: searchData.end_time || undefined
  })
    .then(({ data }) => {
      tableData.value = data.page_info
      paginationData.total = data.total_count
      // 根据id获取row
      if (task_id.value != undefined) {
        const item = tableData.value.filter((item) => {
          return item.task_id == task_id.value
        })
        item && item.length == 1 && setCurrent(item[0])
      }
    })
    .catch(() => {
      tableData.value = []
    })
    .finally(() => {
      loading.value = false
    })
}
const showDialog = () => {
  task_id.value = undefined
  resetSearch()
  handleSearch()
}
const closeDialog = () => {
  emit("closeDialog", undefined)
}

const handleConfirm = () => {
  if (task_id.value == undefined) {
    ElMessage.warning("请选择接入数据！！")
    return
  }
  loading.value = true
  dataAccessApi(task_id.value)
    .then(() => {
      ElMessage.success("操作成功")
      emit("closeDialog", "refresh")
    })
    .finally(() => {
      loading.value = false
    })
}

const taskModeMap = computed<{ [propName in TASK_MODE]: string }>(() => {
  return taskModeOptions.value.reduce(
    (acc, curr) => {
      acc[curr.value] = curr.name
      return acc
    },
    {} as { [propName in TASK_MODE]: string }
  )
})

watch(
  () => [props.visible],
  () => {
    dialogVisible.value = props.visible
    if (props.visible) {
      showDialog()
    }
  }
)

/** 监听分页参数的变化 */
watch([() => paginationData.currentPage, () => paginationData.pageSize], getTableData, { immediate: true })
</script>
<template>
  <el-dialog title="数据接入" v-model="dialogVisible" width="1000" draggable @close="closeDialog">
    <el-card v-loading="loading" shadow="never" class="search-wrapper">
      <el-form ref="searchFormRef" :inline="true" :model="searchData">
        <el-form-item prop="task_name" label="任务名称">
          <el-input v-model="searchData.task_name" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="task_mode" label="任务模式">
          <el-select v-model="searchData.task_mode" clearable placeholder="请选择" style="width: 240px">
            <el-option v-for="item in taskModeOptions" :key="item.value" :label="item.name" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-radio-group v-model="task_id">
      <el-table
        ref="singleTableRef"
        :data="tableData"
        style="width: 100%"
        border
        show-overflow-tooltip
        highlight-current-row
        table-layout="fixed"
        @current-change="handleRowChange"
      >
        <!-- <el-table-column type="index" label="序号" width="100" align="center" /> -->
        <el-table-column label="选择" width="80" align="center">
          <template #default="{ row }">
            <el-radio :value="row.task_id" />
          </template>
        </el-table-column>
        <el-table-column prop="task_name" label="任务名称" width="220" />
        <el-table-column label="任务模式" width="180">
          <template #default="{ row }">
            {{ taskModeMap[JSON.parse(row.task_param).task_config.mode as TASK_MODE] }}
          </template>
        </el-table-column>
        <el-table-column prop="create_time" label="创建时间" width="180" />
        <el-table-column prop="task_describe" label="任务描述" />
      </el-table>
    </el-radio-group>
    <div class="pager-wrapper mt-5">
      <el-pagination
        background
        :layout="paginationData.layout"
        :page-sizes="paginationData.pageSizes"
        :total="paginationData.total"
        :page-size="paginationData.pageSize"
        :currentPage="paginationData.currentPage"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="closeDialog">取 消</el-button>
        <el-button :loading="loading" type="primary" @click="handleConfirm">确 定</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<style lang="scss" scoped>
@import "@/styles/custom.scss";

.el-radio-group {
  width: 100%;
}
.el-radio.el-radio--large {
  height: auto;
}
</style>
